package ink.xiaobaibai.parameterValid;

import org.springframework.stereotype.Component;

import java.lang.annotation.Annotation;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @description: params参数校验类管理者
 * @author: 小白白
 * @create: 2021-05-23
 **/

@Component
public class ParameterValidManager {

    private ConcurrentHashMap<String, ParameterValid> map = new ConcurrentHashMap<>();

    public ParameterResult valid(Annotation annotation, Object value) throws IllegalAccessException, InstantiationException {
        BaseParameter baseParameter = annotation.annotationType().getAnnotation(BaseParameter.class);
        /**
         * 来两个: 一个需要初始化的,一个无需初始化的
         */
        Class aClass = baseParameter.validClass();
        Class[] interfaces = aClass.getInterfaces();
        for (Class interfaceClass : interfaces) {
            if (interfaceClass == ParameterValid.class) {
                //从缓存中拿
                ParameterValid parameterValid = this.map.get(aClass.getName());
                if (parameterValid == null) {
                    parameterValid = (ParameterValid) aClass.newInstance();
                    this.map.put(aClass.getName(), parameterValid);
                }
                return parameterValid.valid(value, annotation);
            }
            if (interfaceClass == ParameterValidHaveInit.class) {
                //每次都新建
                ParameterValidHaveInit parameterValidHaveInit = (ParameterValidHaveInit) aClass.newInstance();
                parameterValidHaveInit.init(annotation);
                return parameterValidHaveInit.valid(value, annotation);
            }
        }
        //不会走到这
        throw new RuntimeException("error Not Fount ParameterValidInterface");
    }

}
